<?php

/**
 * 
 *
 * @version 1.107
 * @package entity
 */
class AlaniaInformacionModel extends Db2PhpEntityBase implements Db2PhpEntityModificationTracking {

    private static $CLASS_NAME = 'AlaniaInformacionModel';

    const SQL_IDENTIFIER_QUOTE = '`';
    const SQL_TABLE_NAME = 'alania_informacion';
    const SQL_INSERT = 'INSERT INTO `alania_informacion` (`id`,`contenido`,`fecha_inicio`,`fecha_final`,`tipo_contenido`,`ultima_actualizacion`,`estado`,`prioridad`,`usuario_ultima_actualizacion`,`usuario_generador`) VALUES (?,?,?,?,?,?,?,?,?,?)';
    const SQL_INSERT_AUTOINCREMENT = 'INSERT INTO `alania_informacion` (`contenido`,`fecha_inicio`,`fecha_final`,`tipo_contenido`,`ultima_actualizacion`,`estado`,`prioridad`,`usuario_ultima_actualizacion`,`usuario_generador`) VALUES (?,?,?,?,?,?,?,?,?)';
    const SQL_UPDATE = 'UPDATE `alania_informacion` SET `id`=?,`contenido`=?,`fecha_inicio`=?,`fecha_final`=?,`tipo_contenido`=?,`ultima_actualizacion`=?,`estado`=?,`prioridad`=?,`usuario_ultima_actualizacion`=?,`usuario_generador`=? WHERE `id`=?';
    const SQL_SELECT_PK = 'SELECT * FROM `alania_informacion` WHERE `id`=?';
    const SQL_DELETE_PK = 'DELETE FROM `alania_informacion` WHERE `id`=?';
    const FIELD_ID = -38048453;
    const FIELD_CONTENIDO = 2124028249;
    const FIELD_FECHA_INICIO = -369220217;
    const FIELD_FECHA_FINAL = 1232100884;
    const FIELD_TIPO_CONTENIDO = -668472754;
    const FIELD_ULTIMA_ACTUALIZACION = 1874134216;
    const FIELD_ESTADO = -1515026042;
    const FIELD_PRIORIDAD = 761575464;
    const FIELD_USUARIO_ULTIMA_ACTUALIZACION = -1601800903;
    const FIELD_USUARIO_GENERADOR = -662108462;

    private static $PRIMARY_KEYS = array(self::FIELD_ID);
    private static $AUTOINCREMENT_FIELDS = array(self::FIELD_ID);
    private static $FIELD_NAMES = array(
        self::FIELD_ID => 'id',
        self::FIELD_CONTENIDO => 'contenido',
        self::FIELD_FECHA_INICIO => 'fecha_inicio',
        self::FIELD_FECHA_FINAL => 'fecha_final',
        self::FIELD_TIPO_CONTENIDO => 'tipo_contenido',
        self::FIELD_ULTIMA_ACTUALIZACION => 'ultima_actualizacion',
        self::FIELD_ESTADO => 'estado',
        self::FIELD_PRIORIDAD => 'prioridad',
        self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => 'usuario_ultima_actualizacion',
        self::FIELD_USUARIO_GENERADOR => 'usuario_generador');
    private static $PROPERTY_NAMES = array(
        self::FIELD_ID => 'id',
        self::FIELD_CONTENIDO => 'contenido',
        self::FIELD_FECHA_INICIO => 'fechaInicio',
        self::FIELD_FECHA_FINAL => 'fechaFinal',
        self::FIELD_TIPO_CONTENIDO => 'tipoContenido',
        self::FIELD_ULTIMA_ACTUALIZACION => 'ultimaActualizacion',
        self::FIELD_ESTADO => 'estado',
        self::FIELD_PRIORIDAD => 'prioridad',
        self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => 'usuarioUltimaActualizacion',
        self::FIELD_USUARIO_GENERADOR => 'usuarioGenerador');
    private static $PROPERTY_TYPES = array(
        self::FIELD_ID => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_CONTENIDO => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_FECHA_INICIO => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_FECHA_FINAL => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_TIPO_CONTENIDO => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_ULTIMA_ACTUALIZACION => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_ESTADO => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_PRIORIDAD => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_USUARIO_GENERADOR => Db2PhpEntity::PHP_TYPE_INT);
    private static $FIELD_TYPES = array(
        self::FIELD_ID => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_CONTENIDO => array(Db2PhpEntity::JDBC_TYPE_LONGVARCHAR, 65535, 0, false),
        self::FIELD_FECHA_INICIO => array(Db2PhpEntity::JDBC_TYPE_TIMESTAMP, 19, 0, false),
        self::FIELD_FECHA_FINAL => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 45, 0, true),
        self::FIELD_TIPO_CONTENIDO => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_ULTIMA_ACTUALIZACION => array(Db2PhpEntity::JDBC_TYPE_TIMESTAMP, 19, 0, false),
        self::FIELD_ESTADO => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_PRIORIDAD => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_USUARIO_GENERADOR => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false));
    private static $DEFAULT_VALUES = array(
        self::FIELD_ID => null,
        self::FIELD_CONTENIDO => '',
        self::FIELD_FECHA_INICIO => '',
        self::FIELD_FECHA_FINAL => null,
        self::FIELD_TIPO_CONTENIDO => 0,
        self::FIELD_ULTIMA_ACTUALIZACION => '',
        self::FIELD_ESTADO => 0,
        self::FIELD_PRIORIDAD => 0,
        self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => 0,
        self::FIELD_USUARIO_GENERADOR => 0);
    private $id;
    private $contenido;
    private $fechaInicio;
    private $fechaFinal;
    private $tipoContenido;
    private $ultimaActualizacion;
    private $estado;
    private $prioridad;
    private $usuarioUltimaActualizacion;
    private $usuarioGenerador;

    /**
     * set value for id 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @param mixed $id
     * @return AlaniaInformacionModel
     */
    public function &setId($id) {
        $this->notifyChanged(self::FIELD_ID, $this->id, $id);
        $this->id = $id;
        return $this;
    }

    /**
     * get value for id 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @return mixed
     */
    public function getId() {
        return $this->id;
    }

    /**
     * set value for contenido 
     *
     * type:TEXT,size:65535,default:null
     *
     * @param mixed $contenido
     * @return AlaniaInformacionModel
     */
    public function &setContenido($contenido) {
        $this->notifyChanged(self::FIELD_CONTENIDO, $this->contenido, $contenido);
        $this->contenido = $contenido;
        return $this;
    }

    /**
     * get value for contenido 
     *
     * type:TEXT,size:65535,default:null
     *
     * @return mixed
     */
    public function getContenido() {
        return $this->contenido;
    }

    /**
     * set value for fecha_inicio 
     *
     * type:DATETIME,size:19,default:null
     *
     * @param mixed $fechaInicio
     * @return AlaniaInformacionModel
     */
    public function &setFechaInicio($fechaInicio) {
        $this->notifyChanged(self::FIELD_FECHA_INICIO, $this->fechaInicio, $fechaInicio);
        $this->fechaInicio = $fechaInicio;
        return $this;
    }

    /**
     * get value for fecha_inicio 
     *
     * type:DATETIME,size:19,default:null
     *
     * @return mixed
     */
    public function getFechaInicio() {
        return $this->fechaInicio;
    }

    /**
     * set value for fecha_final 
     *
     * type:VARCHAR,size:45,default:null,nullable
     *
     * @param mixed $fechaFinal
     * @return AlaniaInformacionModel
     */
    public function &setFechaFinal($fechaFinal) {
        $this->notifyChanged(self::FIELD_FECHA_FINAL, $this->fechaFinal, $fechaFinal);
        $this->fechaFinal = $fechaFinal;
        return $this;
    }

    /**
     * get value for fecha_final 
     *
     * type:VARCHAR,size:45,default:null,nullable
     *
     * @return mixed
     */
    public function getFechaFinal() {
        return $this->fechaFinal;
    }

    /**
     * set value for tipo_contenido 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $tipoContenido
     * @return AlaniaInformacionModel
     */
    public function &setTipoContenido($tipoContenido) {
        $this->notifyChanged(self::FIELD_TIPO_CONTENIDO, $this->tipoContenido, $tipoContenido);
        $this->tipoContenido = $tipoContenido;
        return $this;
    }

    /**
     * get value for tipo_contenido 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getTipoContenido() {
        return $this->tipoContenido;
    }

    /**
     * set value for ultima_actualizacion 
     *
     * type:DATETIME,size:19,default:null
     *
     * @param mixed $ultimaActualizacion
     * @return AlaniaInformacionModel
     */
    public function &setUltimaActualizacion($ultimaActualizacion) {
        $this->notifyChanged(self::FIELD_ULTIMA_ACTUALIZACION, $this->ultimaActualizacion, $ultimaActualizacion);
        $this->ultimaActualizacion = $ultimaActualizacion;
        return $this;
    }

    /**
     * get value for ultima_actualizacion 
     *
     * type:DATETIME,size:19,default:null
     *
     * @return mixed
     */
    public function getUltimaActualizacion() {
        return $this->ultimaActualizacion;
    }

    /**
     * set value for estado 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $estado
     * @return AlaniaInformacionModel
     */
    public function &setEstado($estado) {
        $this->notifyChanged(self::FIELD_ESTADO, $this->estado, $estado);
        $this->estado = $estado;
        return $this;
    }

    /**
     * get value for estado 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getEstado() {
        return $this->estado;
    }

    /**
     * set value for prioridad 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $prioridad
     * @return AlaniaInformacionModel
     */
    public function &setPrioridad($prioridad) {
        $this->notifyChanged(self::FIELD_PRIORIDAD, $this->prioridad, $prioridad);
        $this->prioridad = $prioridad;
        return $this;
    }

    /**
     * get value for prioridad 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getPrioridad() {
        return $this->prioridad;
    }

    /**
     * set value for usuario_ultima_actualizacion 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $usuarioUltimaActualizacion
     * @return AlaniaInformacionModel
     */
    public function &setUsuarioUltimaActualizacion($usuarioUltimaActualizacion) {
        $this->notifyChanged(self::FIELD_USUARIO_ULTIMA_ACTUALIZACION, $this->usuarioUltimaActualizacion, $usuarioUltimaActualizacion);
        $this->usuarioUltimaActualizacion = $usuarioUltimaActualizacion;
        return $this;
    }

    /**
     * get value for usuario_ultima_actualizacion 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getUsuarioUltimaActualizacion() {
        return $this->usuarioUltimaActualizacion;
    }

    /**
     * set value for usuario_generador 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $usuarioGenerador
     * @return AlaniaInformacionModel
     */
    public function &setUsuarioGenerador($usuarioGenerador) {
        $this->notifyChanged(self::FIELD_USUARIO_GENERADOR, $this->usuarioGenerador, $usuarioGenerador);
        $this->usuarioGenerador = $usuarioGenerador;
        return $this;
    }

    /**
     * get value for usuario_generador 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getUsuarioGenerador() {
        return $this->usuarioGenerador;
    }

    /**
     * Get table name
     *
     * @return string
     */
    public static function getTableName() {
        return self::SQL_TABLE_NAME;
    }

    /**
     * Get array with field id as index and field name as value
     *
     * @return array
     */
    public static function getFieldNames() {
        return self::$FIELD_NAMES;
    }

    /**
     * Get array with field id as index and property name as value
     *
     * @return array
     */
    public static function getPropertyNames() {
        return self::$PROPERTY_NAMES;
    }

    /**
     * get the field name for the passed field id.
     *
     * @param int $fieldId
     * @param bool $fullyQualifiedName true if field name should be qualified by table name
     * @return string field name for the passed field id, null if the field doesn't exist
     */
    public static function getFieldNameByFieldId($fieldId, $fullyQualifiedName = true) {
        if (!array_key_exists($fieldId, self::$FIELD_NAMES)) {
            return null;
        }
        $fieldName = self::SQL_IDENTIFIER_QUOTE . self::$FIELD_NAMES[$fieldId] . self::SQL_IDENTIFIER_QUOTE;
        if ($fullyQualifiedName) {
            return self::SQL_IDENTIFIER_QUOTE . self::SQL_TABLE_NAME . self::SQL_IDENTIFIER_QUOTE . '.' . $fieldName;
        }
        return $fieldName;
    }

    /**
     * Get array with field ids of identifiers
     *
     * @return array
     */
    public static function getIdentifierFields() {
        return self::$PRIMARY_KEYS;
    }

    /**
     * Get array with field ids of autoincrement fields
     *
     * @return array
     */
    public static function getAutoincrementFields() {
        return self::$AUTOINCREMENT_FIELDS;
    }

    /**
     * Get array with field id as index and property type as value
     *
     * @return array
     */
    public static function getPropertyTypes() {
        return self::$PROPERTY_TYPES;
    }

    /**
     * Get array with field id as index and field type as value
     *
     * @return array
     */
    public static function getFieldTypes() {
        return self::$FIELD_TYPES;
    }

    /**
     * Assign default values according to table
     * 
     */
    public function assignDefaultValues() {
        $this->assignByArray(self::$DEFAULT_VALUES);
    }

    /**
     * return hash with the field name as index and the field value as value.
     *
     * @return array
     */
    public function toHash() {
        $array = $this->toArray();
        $hash = array();
        foreach ($array as $fieldId => $value) {
            $hash[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        return $hash;
    }

    /**
     * return array with the field id as index and the field value as value.
     *
     * @return array
     */
    public function toArray() {
        return array(
            self::FIELD_ID => $this->getId(),
            self::FIELD_CONTENIDO => $this->getContenido(),
            self::FIELD_FECHA_INICIO => $this->getFechaInicio(),
            self::FIELD_FECHA_FINAL => $this->getFechaFinal(),
            self::FIELD_TIPO_CONTENIDO => $this->getTipoContenido(),
            self::FIELD_ULTIMA_ACTUALIZACION => $this->getUltimaActualizacion(),
            self::FIELD_ESTADO => $this->getEstado(),
            self::FIELD_PRIORIDAD => $this->getPrioridad(),
            self::FIELD_USUARIO_ULTIMA_ACTUALIZACION => $this->getUsuarioUltimaActualizacion(),
            self::FIELD_USUARIO_GENERADOR => $this->getUsuarioGenerador());
    }

    /**
     * return array with the field id as index and the field value as value for the identifier fields.
     *
     * @return array
     */
    public function getPrimaryKeyValues() {
        return array(
            self::FIELD_ID => $this->getId());
    }

    /**
     * cached statements
     *
     * @var array<string,array<string,PDOStatement>>
     */
    private static $stmts = array();
    private static $cacheStatements = true;

    /**
     * prepare passed string as statement or return cached if enabled and available
     *
     * @param PDO $db
     * @param string $statement
     * @return PDOStatement
     */
    protected static function prepareStatement(PDO $db, $statement) {
        if (self::isCacheStatements()) {
            if (in_array($statement, array(self::SQL_INSERT, self::SQL_INSERT_AUTOINCREMENT, self::SQL_UPDATE, self::SQL_SELECT_PK, self::SQL_DELETE_PK))) {
                $dbInstanceId = spl_object_hash($db);
                if (empty(self::$stmts[$statement][$dbInstanceId])) {
                    self::$stmts[$statement][$dbInstanceId] = $db->prepare($statement);
                }
                return self::$stmts[$statement][$dbInstanceId];
            }
        }
        return $db->prepare($statement);
    }

    /**
     * Enable statement cache
     *
     * @param bool $cache
     */
    public static function setCacheStatements($cache) {
        self::$cacheStatements = true == $cache;
    }

    /**
     * Check if statement cache is enabled
     *
     * @return bool
     */
    public static function isCacheStatements() {
        return self::$cacheStatements;
    }

    /**
     * check if this instance exists in the database
     *
     * @param PDO $db
     * @return bool
     */
    public function existsInDatabase(PDO $db) {
        $filter = array();
        foreach ($this->getPrimaryKeyValues() as $fieldId => $value) {
            $filter[] = new DFC($fieldId, $value, DFC::EXACT_NULLSAFE);
        }
        return 0 != count(self::findByFilter($db, $filter, true));
    }

    /**
     * Update to database if exists, otherwise insert
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateInsertToDatabase(PDO $db) {
        if ($this->existsInDatabase($db)) {
            return $this->updateToDatabase($db);
        } else {
            return $this->insertIntoDatabase($db);
        }
    }

    /**
     * Query by Example.
     *
     * Match by attributes of passed example instance and return matched rows as an array of AlaniaInformacionModel instances
     *
     * @param PDO $db a PDO Database instance
     * @param AlaniaInformacionModel $example an example instance defining the conditions. All non-null properties will be considered a constraint, null values will be ignored.
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaInformacionModel[]
     */
    public static function findByExample(PDO $db, AlaniaInformacionModel $example, $and = true, $sort = null) {
        $exampleValues = $example->toArray();
        $filter = array();
        foreach ($exampleValues as $fieldId => $value) {
            if (null !== $value) {
                $filter[$fieldId] = $value;
            }
        }
        return self::findByFilter($db, $filter, $and, $sort);
    }

    /**
     * Query by filter.
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * Will return matched rows as an array of AlaniaInformacionModel instances.
     *
     * @param PDO $db a PDO Database instance
     * @param array $filter array of DFC instances defining the conditions
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaInformacionModel[]
     */
    public static function findByFilter(PDO $db, $filter, $and = true, $sort = null) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        $sql = 'SELECT * FROM `alania_informacion`'
                . self::buildSqlWhere($filter, $and, false, true)
                . self::buildSqlOrderBy($sort);

        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        return self::fromStatement($stmt);
    }

    /**
     * Will execute the passed statement and return the result as an array of AlaniaInformacionModel instances
     *
     * @param PDOStatement $stmt
     * @return AlaniaInformacionModel[]
     */
    public static function fromStatement(PDOStatement $stmt) {
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        return self::fromExecutedStatement($stmt);
    }

    /**
     * returns the result as an array of AlaniaInformacionModel instances without executing the passed statement
     *
     * @param PDOStatement $stmt
     * @return AlaniaInformacionModel[]
     */
    public static function fromExecutedStatement(PDOStatement $stmt) {
        $resultInstances = array();
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $o = new AlaniaInformacionModel();
            $o->assignByHash($result);
            $o->notifyPristine();
            $resultInstances[] = $o;
        }
        $stmt->closeCursor();
        return $resultInstances;
    }

    /**
     * Get sql WHERE part from filter.
     *
     * @param array $filter
     * @param bool $and
     * @param bool $fullyQualifiedNames true if field names should be qualified by table name
     * @param bool $prependWhere true if WHERE should be prepended to conditions
     * @return string
     */
    public static function buildSqlWhere($filter, $and, $fullyQualifiedNames = true, $prependWhere = false) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        return $filter->buildSqlWhere(new self::$CLASS_NAME, $fullyQualifiedNames, $prependWhere);
    }

    /**
     * get sql ORDER BY part from DSCs
     *
     * @param array $sort array of DSC instances
     * @return string
     */
    protected static function buildSqlOrderBy($sort) {
        return DSC::buildSqlOrderBy(new self::$CLASS_NAME, $sort);
    }

    /**
     * bind values from filter to statement
     *
     * @param PDOStatement $stmt
     * @param DFCInterface $filter
     */
    public static function bindValuesForFilter(PDOStatement &$stmt, DFCInterface $filter) {
        $filter->bindValuesForFilter(new self::$CLASS_NAME, $stmt);
    }

    /**
     * Execute select query and return matched rows as an array of AlaniaInformacionModel instances.
     *
     * The query should of course be on the table for this entity class and return all fields.
     *
     * @param PDO $db a PDO Database instance
     * @param string $sql
     * @return AlaniaInformacionModel[]
     */
    public static function findBySql(PDO $db, $sql) {
        $stmt = $db->query($sql);
        return self::fromExecutedStatement($stmt);
    }

    /**
     * Delete rows matching the filter
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * @param PDO $db
     * @param array $filter
     * @param bool $and
     * @return mixed
     */
    public static function deleteByFilter(PDO $db, $filter, $and = true) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        if (0 == count($filter)) {
            throw new InvalidArgumentException('refusing to delete without filter'); // just comment out this line if you are brave
        }
        $sql = 'DELETE FROM `alania_informacion`'
                . self::buildSqlWhere($filter, $and, false, true);
        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Assign values from array with the field id as index and the value as value
     *
     * @param array $array
     */
    public function assignByArray($array) {
        $result = array();
        foreach ($array as $fieldId => $value) {
            $result[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        $this->assignByHash($result);
    }

    /**
     * Assign values from hash where the indexes match the tables field names
     *
     * @param array $result
     */
    public function assignByHash($result) {
        $this->setId($result['id']);
        $this->setContenido($result['contenido']);
        $this->setFechaInicio($result['fecha_inicio']);
        $this->setFechaFinal($result['fecha_final']);
        $this->setTipoContenido($result['tipo_contenido']);
        $this->setUltimaActualizacion($result['ultima_actualizacion']);
        $this->setEstado($result['estado']);
        $this->setPrioridad($result['prioridad']);
        $this->setUsuarioUltimaActualizacion($result['usuario_ultima_actualizacion']);
        $this->setUsuarioGenerador($result['usuario_generador']);
    }

    /**
     * Get element instance by it's primary key(s).
     * Will return null if no row was matched.
     *
     * @param PDO $db
     * @return AlaniaInformacionModel
     */
    public static function findById(PDO $db, $id) {
        $stmt = self::prepareStatement($db, self::SQL_SELECT_PK);
        $stmt->bindValue(1, $id);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$result) {
            return null;
        }
        $o = new AlaniaInformacionModel();
        $o->assignByHash($result);
        $o->notifyPristine();
        return $o;
    }

    /**
     * Bind all values to statement
     *
     * @param PDOStatement $stmt
     */
    protected function bindValues(PDOStatement &$stmt) {
        $stmt->bindValue(1, $this->getId());
        $stmt->bindValue(2, $this->getContenido());
        $stmt->bindValue(3, $this->getFechaInicio());
        $stmt->bindValue(4, $this->getFechaFinal());
        $stmt->bindValue(5, $this->getTipoContenido());
        $stmt->bindValue(6, $this->getUltimaActualizacion());
        $stmt->bindValue(7, $this->getEstado());
        $stmt->bindValue(8, $this->getPrioridad());
        $stmt->bindValue(9, $this->getUsuarioUltimaActualizacion());
        $stmt->bindValue(10, $this->getUsuarioGenerador());
    }

    /**
     * Insert this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function insertIntoDatabase(PDO $db) {
        if (null === $this->getId()) {
            $stmt = self::prepareStatement($db, self::SQL_INSERT_AUTOINCREMENT);
            $stmt->bindValue(1, $this->getContenido());
            $stmt->bindValue(2, $this->getFechaInicio());
            $stmt->bindValue(3, $this->getFechaFinal());
            $stmt->bindValue(4, $this->getTipoContenido());
            $stmt->bindValue(5, $this->getUltimaActualizacion());
            $stmt->bindValue(6, $this->getEstado());
            $stmt->bindValue(7, $this->getPrioridad());
            $stmt->bindValue(8, $this->getUsuarioUltimaActualizacion());
            $stmt->bindValue(9, $this->getUsuarioGenerador());
        } else {
            $stmt = self::prepareStatement($db, self::SQL_INSERT);
            $this->bindValues($stmt);
        }
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $lastInsertId = $db->lastInsertId();
        if (false !== $lastInsertId) {
            $this->setId($lastInsertId);
        }
        $stmt->closeCursor();
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Update this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateToDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_UPDATE);
        $this->bindValues($stmt);
        $stmt->bindValue(11, $this->getId());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Delete this instance from the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function deleteFromDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_DELETE_PK);
        $stmt->bindValue(1, $this->getId());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Fetch AlaniaLogModel's which this AlaniaInformacionModel references.
     * `alania_informacion`.`id` -> `alania_log`.`informacion`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaLogModel[]
     */
    public function fetchAlaniaLogModelCollection(PDO $db, $sort = null) {
        $filter = array(AlaniaLogModel::FIELD_INFORMACION => $this->getId());
        return AlaniaLogModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch PermisosInformacionGrupoModel's which this AlaniaInformacionModel references.
     * `alania_informacion`.`id` -> `permisos_informacion_grupo`.`informacion`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return PermisosInformacionGrupoModel[]
     */
    public function fetchPermisosInformacionGrupoModelCollection(PDO $db, $sort = null) {
        $filter = array(PermisosInformacionGrupoModel::FIELD_INFORMACION => $this->getId());
        return PermisosInformacionGrupoModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch PermisosInformacionUsuarioModel's which this AlaniaInformacionModel references.
     * `alania_informacion`.`id` -> `permisos_informacion_usuario`.`informacion`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return PermisosInformacionUsuarioModel[]
     */
    public function fetchPermisosInformacionUsuarioModelCollection(PDO $db, $sort = null) {
        $filter = array(PermisosInformacionUsuarioModel::FIELD_INFORMACION => $this->getId());
        return PermisosInformacionUsuarioModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch AlaniaUsuarioModel which references this AlaniaInformacionModel. Will return null in case reference is invalid.
     * `alania_informacion`.`usuario_generador` -> `alania_usuario`.`id_usuario`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaUsuarioModel
     */
//    public function fetchAlaniaContenidosModel(PDO $db, $sort = null) {
//        $filter = array(AlaniaContenidosModel::FIELD_ID => $this->getTipoContenido());
//        $result = AlaniaContenidosModel::findByFilter($db, $filter, true, $sort);
//        return empty($result) ? null : $result[0];
//    }

    /**
     * Fetch AlaniaUsuarioModel which references this AlaniaInformacionModel. Will return null in case reference is invalid.
     * `alania_informacion`.`usuario_ultima_actualizacion` -> `alania_usuario`.`id_usuario`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaContenidosModel
     */
    public function fetchAlaniaContenidosModel(PDO $db, $sort = null) {
        $filter = array(AlaniaContenidosModel::FIELD_ID => $this->getTipoContenido());
        $result = AlaniaContenidosModel::findByFilter($db, $filter, true, $sort);
        return empty($result) ? null : $result[0];
    }

    /**
     * Fetch AlaniaEstadosModel which references this AlaniaInformacionModel. Will return null in case reference is invalid.
     * `alania_informacion`.`estado` -> `alania_estados`.`id_estado`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaEstadosModel
     */
    public function fetchAlaniaEstadosModel(PDO $db, $sort = null) {
        $filter = array(AlaniaEstadosModel::FIELD_ID_ESTADO => $this->getEstado());
        $result = AlaniaEstadosModel::findByFilter($db, $filter, true, $sort);
        return empty($result) ? null : $result[0];
    }

    /**
     * Fetch AlaniaPrioridadModel which references this AlaniaInformacionModel. Will return null in case reference is invalid.
     * `alania_informacion`.`prioridad` -> `alania_prioridad`.`id_prioridad`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaPrioridadModel
     */
    public function fetchAlaniaPrioridadModel(PDO $db, $sort = null) {
        $filter = array(AlaniaPrioridadModel::FIELD_ID_PRIORIDAD => $this->getPrioridad());
        $result = AlaniaPrioridadModel::findByFilter($db, $filter, true, $sort);
        return empty($result) ? null : $result[0];
    }

    /**
     * return array with the property name as index and the field value as value.
     * ezComponents support method
     *
     * @return array
     */
    public function getState() {
        $array = $this->toArray();
        $state = array();
        foreach ($array as $fieldId => $value) {
            $state[self::$PROPERTY_NAMES[$fieldId]] = $value;
        }
        return $state;
    }

    /**
     * Assign values from hash where the indexes match the property names.
     * ezComponents support method
     *
     * @param array $state
     */
    public function setState(array $state) {
        $propertyNameToFieldId = array_flip(self::$PROPERTY_NAMES);
        $hash = $this->toHash();
        foreach ($state as $propertyName => $value) {
            $hash[self::$FIELD_NAMES[$propertyNameToFieldId[$propertyName]]] = $value;
        }
        $this->assignByHash($hash);
    }

    /**
     * get persistence definition for ezComponents
     *
     * @return ezcPersistentObjectDefinition
     */
    public static function toEzcPersistentObjectDefinition() {
        static $typeMapping = array(
    Db2PhpEntity::PHP_TYPE_BOOL => ezcPersistentObjectProperty::PHP_TYPE_BOOL,
    Db2PhpEntity::PHP_TYPE_INT => ezcPersistentObjectProperty::PHP_TYPE_INT,
    Db2PhpEntity::PHP_TYPE_FLOAT => ezcPersistentObjectProperty::PHP_TYPE_FLOAT,
    Db2PhpEntity::PHP_TYPE_STRING => ezcPersistentObjectProperty::PHP_TYPE_STRING
        );
        $def = new ezcPersistentObjectDefinition();
        $def->table = self::SQL_TABLE_NAME;
        $def->class = 'AlaniaInformacionModel';
        if (!empty(self::$PRIMARY_KEYS)) {
            $pkField = self::$PRIMARY_KEYS[0];
            $def->idProperty = new ezcPersistentObjectIdProperty();
            $def->idProperty->columnName = self::$FIELD_NAMES[$pkField];
            $def->idProperty->propertyName = self::$PROPERTY_NAMES[$pkField];
            $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
                    in_array($pkField, self::$AUTOINCREMENT_FIELDS) ? 'ezcPersistentNativeGenerator' : 'ezcPersistentManualGenerator');
        } else {
            $pkField = null;
        }
        foreach (self::$PROPERTY_NAMES as $fieldId => $propertyName) {
            if ($fieldId !== $pkField) {
                $def->properties[$propertyName] = new ezcPersistentObjectProperty();
                $def->properties[$propertyName]->columnName = self::$FIELD_NAMES[$fieldId];
                $def->properties[$propertyName]->propertyName = $propertyName;
                $def->properties[$propertyName]->propertyType = $typeMapping[self::$PROPERTY_TYPES[$fieldId]];
            }
        }
        return $def;
    }

    /**
     * get element as DOM Document
     *
     * @return DOMDocument
     */
    public function toDOM() {
        return self::hashToDomDocument($this->toHash(), 'AlaniaInformacionModel');
    }

    /**
     * get single AlaniaInformacionModel instance from a DOMElement
     *
     * @param DOMElement $node
     * @return AlaniaInformacionModel
     */
    public static function fromDOMElement(DOMElement $node) {
        $o = new AlaniaInformacionModel();
        $o->assignByHash(self::domNodeToHash($node, self::$FIELD_NAMES, self::$DEFAULT_VALUES, self::$FIELD_TYPES));
        $o->notifyPristine();
        return $o;
    }

    /**
     * get all instances of AlaniaInformacionModel from the passed DOMDocument
     *
     * @param DOMDocument $doc
     * @return AlaniaInformacionModel[]
     */
    public static function fromDOMDocument(DOMDocument $doc) {
        $instances = array();
        foreach ($doc->getElementsByTagName('AlaniaInformacionModel') as $node) {
            $instances[] = self::fromDOMElement($node);
        }
        return $instances;
    }

    public static function fromContenidosModel(PDO $db, $contenido) {
        $contenido = AlaniaContenidosModel::findByName($db, $contenido);
        $example = new AlaniaInformacionModel();
        //include_once 'fire/FirePHP.class.php';
        //$firephp = FirePHP::getInstance(true);
        $example->setTipoContenido($contenido->getId());
        $ret = AlaniaInformacionModel::findByExample($db, $example);
        $arr = array();
        $cont = array();
        $x = array("menu" => array(
                array("name" => "Home", "link" => "index.php", "selected" => true),
                array("name" => "FAQ", "link" => "index.php/FAQ/", "selected" => null),
                array("name" => "Documentation", "link" => "index.php/doc/", "selected" => null)));
        ////$firephp->log(json_encode($x),"array_de");
        foreach ($ret as $p) {
            /* @var $p ProductModel */
            ////$firephp->log(json_decode('{"si": [[{"href": "prueba"},{"titulo": "prueba"}],[{"href": "prueba"},{"titulo": "prueba"}]]}', TRUE), "json");
            $a = json_decode($p->getContenido(), TRUE);
            $cont["contenido"] = $a;
            //$firephp->log($_SESSION['usuario'],"session");
            $user = new LoggedUser($_SESSION['usuario']);
            //$firephp = FirePHP::getInstance(true);
            
            //$firephp->log($p->getId());
//            //$firephp->log(gettype($p->getId()));
            $cont["permiso"] = $user->checkPermissions($db, $p->getId());
            array_push($arr, $cont);
//            //$firephp->log($a, "arr");
            //array_push($arr, $a);
            ////$firephp->log($p->getID());
        }
        //return $ret->toArray();
        ////$firephp->log($arr, "fin");
        return $arr;
    }

    private function getPermisos($db, $id) {
        $permiso = "00";
        //$firephp = FirePHP::getInstance(true);
        $this->getId();
        ////$firephp->log($u, "usuario");
        //$user = AlaniaUsuarioModel::findById($db, isset($_SESSION['usuario']) ? $_SESSION['usuario'] : 7);
        ////$firephp->log($user, "usuario");
        //$usergroups=$user->fetchPerfilDependenciaUsuarioModelCollection($db);
        ////$firephp->log($usergroups, "perfiles");
        $porg = $this->fetchPermisosInformacionGrupoModelCollection($db);
        $poru = $this->fetchPermisosInformacionUsuarioModelCollection($db);
        ////$firephp = FirePHP::getInstance(true);
        $user = $_SESSION['usuario'];

        //$firephp->log($this->getId(), "id");
        //$firephp->log($porg, "porg");
        //$firephp->log($poru, "poru");
        //$firephp->log($_SESSION['usuario'], "usuario");
        return $permiso;
    }

}

?>